<?php

namespace App\Http\Controllers\Tca;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class TcaController extends Controller
{
    //添加轮播图的视图
    public function getAdd()
    {
        $tca = DB::table('tcarousel')->max('id');
        $data = DB::table('tcarousel')->where('id','=',$tca)->get();
        //解析模板
        return view('Admin.Tca.add',['data'=>$data]);
    }

    //添加轮播图
    public function postInsert(Request $request)
    {
        $tca = DB::table('tcarousel')->count();
        if($tca >= 6){
            return back();
        }
        $data = $request->except('_token');
        $data['img'] = $this->upload($request);
        $res = DB::table('tcarousel')->insertGetId($data);
        if($res){
          return redirect('admin/index');
        }
    }

    //轮播图的删除
    public function getDelete($id)
    {
        $tca = DB::table('tcarousel')->count();
        if($tca <= 3){
          return back();
        }
        $del = DB::table('tcarousel')->where('id',$id)->delete();
        $data = DB::table('tcarousel')->get();
        return view('Admin.Tca.list',['data'=>$data]);
    }

    //轮播图列表
    public function getList()
    {
        $data = DB::table('tcarousel')->get();
        //解析模板
        return view('Admin.Tca.list',['data'=>$data]);
    }

    //轮播图修改的视图
    public function getEdit($id)
    {
        $data = DB::table('tcarousel')->where('id',$id)->first();
        //dd($data);
        return view('Admin.Tca.edit',['data'=>$data]);
    }

    //轮播图修改
    public function postUpdate(Request $request)
    {
        $data = $request->except('_token');
        if($request->hasFile('img')){
           //调用方法进行头像的上传操作
           $data['img'] = $this->upload($request);
        }
        $res = DB::table('tcarousel')->where('id',$data['id'])->update($data);
        if($res){
            return redirect('admin/index')->with('success','用户修改成功');
        }else{
            return back()->with('error','用户修改失败');
        }
    }

    //图片上传
    public function upload($request)
    {
      if ($request->hasfile('img')) {
          $aa = $request->file('img')->getClientMimeType();
          $type = array('image/png','image/gif','image/jpeg');
          if(!in_array($aa, $type)){
              die('请选择正确的文件类型');
          }
          $name = md5(time()+rand(1,999999));
          $su = $request->file('img')->getClientOriginalExtension();
          $request->file('img')->move('./Public/Uploads',$name.'.'.$su);
          return '/Public/Uploads/'.$name.'.'.$su;
      }
    }
}
